package cn.acewill.yxd.yunxundian.ui.sign;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.WriteEvaluationAdapter;
import cn.acewill.yxd.yunxundian.model.CommonMapBean;
import cn.acewill.yxd.yunxundian.model.RMain;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.Shop;
import cn.acewill.yxd.yunxundian.model.SignUpInfo;
import cn.acewill.yxd.yunxundian.model.rJson;
import cn.acewill.yxd.yunxundian.model.r_trrAddtion;
import cn.acewill.yxd.yunxundian.model.sType;
import cn.acewill.yxd.yunxundian.model.tempLostRR;
import cn.acewill.yxd.yunxundian.pubClass.AsynData;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.pubClass.signuppanel;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.utils.MaterialDialogUtils;
import cn.acewill.yxd.yunxundian.utils.baiduUtils.BaiduMapUtils;

/**
 * Created by XXX on 2017/11/30.
 * 编辑评估项
 */

public class WrittingEvaluationListActivity extends BaseActivity{

    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    public int schid;
    private List<tempLostRR> temp;
    private TextView titleText;
    WriteEvaluationAdapter adapter;
    private RecyclerView myRecycle;
    private  RMain.QBean qinfo;
    private int reportMainid;
    private LinearLayout noDataView;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //      CacheActivity.addActivity(this);
     //   Eyes.translucentStatusBar(this,true);
        setContentView(R.layout.write_evaluation_view);
        initView();
    }
    @Override
    protected void onResume() {
        super.onResume();
        try {
            checkCanDoReport();
            getTishiInfo();
            LoadLocalData();
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_eva_submit,menu);
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.tishi:

                String title;
                if (temp == null || temp.size() <= 0) {
                    title = "该评估表尚未填写任何失分项，是否进行提交";
                } else {
                    title = "是否进行数据提交";
                }
                MaterialDialogUtils.showMaterialDialog(WrittingEvaluationListActivity.this, title, "确定", "取消", true, false
                        , new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                Intent in = new Intent(WrittingEvaluationListActivity.this, SendMailActivity.class).putExtra("schId", schid);
                                //添加一个类型，用于关闭当前的页面
                                startActivityForResult(in, 101);
                            }
                        }, new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            }
                        });
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initView(){
        int tag=getIntent().getIntExtra("rrschid",-1);
        titleText = (TextView)findViewById(R.id.titleText);
        noDataView = (LinearLayout) findViewById(R.id.nodata);
        Toolbar toolbar = (Toolbar) findViewById(R.id.myToolBar);
        toolbar.setTitle("");
        toolbar.setNavigationIcon(R.mipmap.back);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        if (tag!=-1){
            schid=tag;
            gudingSchid(schid);
        }
        initRecycle();
    }
    private void initRecycle(){
         myRecycle = (RecyclerView) findViewById(R.id.myRecycle);
        myRecycle.setLayoutManager(new LinearLayoutManager(this));
        myRecycle.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
    }
//
    public void gudingSchid(int thisSchid)
    {
        try {
            CommonMapBean gudingSch=db.selector(CommonMapBean.class).where("cmType","=","gudingsch").findFirst();
            if(gudingSch!=null)
            {
                gudingSch.setCmValue(thisSchid+"");
            }
            else{
                gudingSch=new CommonMapBean();
                gudingSch.setCmValue(thisSchid+"");
            }
            db.saveOrUpdate(gudingSch);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }
    public void checkCanDoReport() throws DbException
    {
        if(schid==0)
            jiuyuanSchid();
        final Schedule thisSch=db.selector(Schedule.class).where("ID","=",schid+"").findFirst();
        refreshScore(schid);

        if(thisSch.getShopID()>0)
        {
            if(thisSch.getStates()==1) {
                SignUpInfo sui = db.selector(SignUpInfo.class).where("shopId", "=", thisSch.getShopID())
                        .and("empId","=", MainActivity.id)
                        .and("outTime","=",null)
                        .findFirst();
                if(sui==null){

                    MaterialDialogUtils.showMoreBtnDialog(this, "当前门店没进行签到，是否去该门店签到？" + "\n" + "tip：签到才能执行任务",
                            "地图查看", "取消", "直接签到", false, true,
                            new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    try {
                                        Shop shop = db.selector(Shop.class).where("ID","=",thisSch.getShopID()).findFirst();
                                        Intent in=new Intent(WrittingEvaluationListActivity.this,SignInActivity.class).putExtra("shopId",thisSch.getShopID());
                                        in.putExtra("xcol",shop.getxCol());
                                        in.putExtra("ycol", shop.getyCol());
                                        in.putExtra("schid",schid);
                                        in.putExtra("shopName", shop.getShopName());
                                        startActivity(in);
                                        finish();
                                    } catch (DbException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    dialog.dismiss();
                                    finish();
                                }
                            }, new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    signLocation();
                                }
                            });
                }
                else{
                    thisSch.setStates(2);
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                    String thistime=df.format(new Date());
                    thistime=thistime.replace(" ","T");
                    thisSch.setRealStartTime(thistime);
                    db.saveOrUpdate(thisSch);
                }
            }
        }
    }

    public void refreshScore(int schid)throws DbException
    {
        String retStr;
        retStr= pubClass.calScoreBySch(schid);
        if (retStr!=null){
            titleText.setText(retStr);
        }
    }

    public void jiuyuanSchid()
    {
        try {
            CommonMapBean gudingSch=db.selector(CommonMapBean.class).where("cmType","=","gudingsch").findFirst();
            if(gudingSch!=null)
            {
                schid=Integer.getInteger(gudingSch.getCmValue(),0);
            }
            else
                schid=0;
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    public void LoadLocalData() throws DbException {
        temp=db.selector(tempLostRR.class).where("schId","=",schid).findAll();
        if (temp!=null&&temp.size()>0){
            noDataView.setVisibility(View.GONE);
        }else{
            noDataView.setVisibility(View.VISIBLE);
        }
        adapter = new WriteEvaluationAdapter(this, temp, new WriteEvaluationAdapter.BtnOnClickLisener() {
            @Override
            public void modifiClick(tempLostRR bean) {
                Intent in=new Intent(WrittingEvaluationListActivity.this,MarkPhotoActivity.class);
                in.putExtra("_ID",bean.get_ID());
                in.putExtra("tag",2);
                in.putExtra("type",bean.getScoreType());
                in.putExtra("schid",schid);
                startActivity(in);
            }
            @Override
            public void deleteClick(final int position) {
                MaterialDialogUtils.showMaterialDialog(WrittingEvaluationListActivity.this, "是否删除当前评估项", "确定", "取消", true,false
                        , new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                try {
                                    tempLostRR bean=temp.get(position);
                                    List<r_trrAddtion> trraList = db.selector(r_trrAddtion.class).where("schid","=",schid).and("rowId","=",bean.getRRowId()).findAll();
                                    if(trraList!=null){
                                        db.delete(trraList);
                                    }
                                    db.deleteById(tempLostRR.class,bean.get_ID());
                                    temp.remove(position);
                                    refreshScore(schid);
                                    // adapter.notifyItemRemoved(position);
                                    adapter.notifyDataSetChanged();
                                    //没数据是否显示提示
                                    if (temp==null||temp.size()<=0){
                                        noDataView.setVisibility(View.VISIBLE);
                                    }
                                } catch (DbException e) {
                                    e.printStackTrace();

                                }
                            }
                        }, new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                dialog.dismiss();
                            }});
            }

            @Override
            public void addEvaClick() {
                Intent in = new Intent(WrittingEvaluationListActivity.this, YxdMajorMainActivity.class).putExtra("schid", schid);
                startActivity(in);
            }

            @SuppressLint("RtlHardcoded")
            @Override
            public void onDesc() {
                if (qinfo != null) {
                    if (qinfo.getDescription() != null && !TextUtils.isEmpty(qinfo.getDescription())) {
                        //创建提示框
                        Log.e("qinof", qinfo.getDescription());
                        AlertDialog.Builder builder = new AlertDialog.Builder(WrittingEvaluationListActivity.this);
                        View dview = LayoutInflater.from(WrittingEvaluationListActivity.this).inflate(R.layout.normal_text_view, (ViewGroup) getWindow().getDecorView(), false);
                        builder.setView(dview);
                        builder.setTitle("提示信息");
                        TextView mytext = (TextView) dview.findViewById(R.id.mytext);
                        mytext.setGravity(Gravity.LEFT);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            mytext.setText(Html.fromHtml(qinfo.getDescription(), Html.FROM_HTML_MODE_COMPACT));
                        } else {
                            mytext.setText(Html.fromHtml(qinfo.getDescription()));
                        }

                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        });
                        builder.show();
                    } else Toast.makeText(WrittingEvaluationListActivity.this, "暂无提示信息", Toast.LENGTH_SHORT).show();
                } else Toast.makeText(WrittingEvaluationListActivity.this, "暂无提示信息", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void goSignature() {
                shopSignIntent();
            }

            @Override
            public void feedBack() {
                startActivity(new Intent(WrittingEvaluationListActivity.this,MulitpleLostRRActivity.class).putExtra("schid",schid));
            }

            @Override
            public void jibenClick() {
                startActivity(new Intent(WrittingEvaluationListActivity.this, JibenInfoActivity.class).putExtra("mainId", reportMainid).putExtra("schid",schid));
                //  Toast.makeText(WrittingEvaluationListActivity.this,"添加基本",Toast.LENGTH_SHORT).show();
            }
        });
        myRecycle.setAdapter(adapter);
    }
    //获取提示的信息
    public void getTishiInfo() throws DbException {
        Schedule schedule = db.selector(Schedule.class).where("ID", "=", schid).findFirst();
        sType type = db.selector(sType.class).where("ID", "=", schedule.getSTypeID()).findFirst();
        rJson rmian = db.selector(rJson.class).where("ID", "=", type.getReportId()).findFirst();
        if (rmian==null){
            showToast(this,"数据错误");
            finish();
            return;
        }
        String json = rmian.getjSon();
        Gson gson = new Gson();
        Type typeList = new TypeToken<ArrayList<RMain>>() {
        }.getType();
        ArrayList<RMain> rMains = gson.fromJson(pubClass.convertToArrayJsonNormal(json), typeList);
        if (rMains!=null&&rMains.size()>0){
            qinfo = rMains.get(0).getQ();
            RMain.TablesBean tablesBean=rMains.get(0).getTables().get(0);
            reportMainid= tablesBean.getQ1().getReportMainID();
        }

    }
    public void shopSignIntent()
    {
        Intent in=new Intent(this,signuppanel.class);
        in.putExtra("rrschid",schid);
        startActivity(in);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 101:
                finish();
                break;
        }
    }

    private LatLng myPosition;
    private boolean isFirstLoc = true;
    private Dialog dialog;
    private int isinrange = 0;
    private int isneedupdateshopXY = 1;
    private int shopId;
    //开启定位
    private void signLocation(){
        BaiduMapUtils.getInstance(this).getLocate(new BaiduMapUtils.OnLocationMapListener() {
            @Override
            public void getCurrLocation(BDLocation location) throws DbException {
                MyLocationData locData = new MyLocationData.Builder()
                        .accuracy(location.getRadius())
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(100).latitude(location.getLatitude())
                        .longitude(location.getLongitude()).build();
                myPosition = new LatLng(location.getLatitude(), location.getLongitude());

                if (isFirstLoc) {
                    isFirstLoc = false;
                    LatLng ll = new LatLng(location.getLatitude(),
                            location.getLongitude());
                    if ((int) location.getAltitude() == 0) {
                        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                            if (ActivityCompat.checkSelfPermission(WrittingEvaluationListActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(WrittingEvaluationListActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                                return;
                            }
                            Location location1 = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location1 != null) {
                                double[] latlng = (pubClass.wgs2bd(location1.getLatitude(), location1.getLongitude()));
                                ll = new LatLng(latlng[0], latlng[1]);
                                myPosition = new LatLng(latlng[0], latlng[1]);
//                                locData = new MyLocationData.Builder()
//                                        .accuracy(location.getRadius())
//                                        // 此处设置开发者获取到的方向信息，顺时针0-360
//                                        .direction(100).latitude(latlng[0])
//                                        .longitude(latlng[1]).build();
                            }
                        }
                    }
                }
                signIn();
            }
        });
    }
    
    public void signIn(){
        try {
            Schedule schedule = db.selector(Schedule.class).where("ID","=",schid).findFirst();
            if (schedule!=null){
                Shop thisShop = db.selector(Shop.class).where("ID","=",schedule.getShopID()).findFirst();
                if (thisShop!=null){
                    shopId = thisShop.getID();
                    double ycol = thisShop.getyCol();
                    double xcol = thisShop.getxCol();
                    Log.e("shopXYCol",ycol+","+xcol);
                    if (MainActivity.signId>0){
                        //签出再签到
                        isneedupdateshopXY=1;
                        signout();

                    }else{
                        //签到
                        if (ycol==0||xcol==0){ //门店无坐标数据
                            isneedupdateshopXY=0;
                            doSignRequest();
                        }else{ //计算坐标差异，用于提示用户
                            isneedupdateshopXY=1;
                            LatLng shoplath = new LatLng(ycol,xcol);
                            showDialog(myPosition,shoplath);
                        }
                    }
                }
            }else{
                showToast(this,"参数错误");
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }


public String getTime(){
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    Date date=new Date(System.currentTimeMillis());
    String signTime=formatter.format(date);
    return signTime;
}



public void saveData(){ //保存本签到地数据
    final SignUpInfo nsi=new SignUpInfo();
    nsi.setEmpId(MainActivity.id);
    nsi.setIsInRange(isinrange);
    nsi.setInTime(getTime());
    nsi.setShopId(shopId);
    nsi.setXCol(myPosition.longitude);
    nsi.setYCol(myPosition.latitude);
    try{
        db.saveOrUpdate(nsi);
        MainActivity.signId=nsi.get_ID();
    } catch (DbException e) {
        e.printStackTrace();
    }
}
    //签到数据请求
    public void doSignRequest(){

        Map<String,String> map=new HashMap<>();
        map.put("task","signUpEmployee");
        map.put("empid", MainActivity.id+"");
        map.put("shopid",shopId+"");
        map.put("lat",""+myPosition.latitude);
        map.put("lng",""+myPosition.longitude);
        map.put("isinrange",isinrange+"");//0 小于1000m，1大于1000m
        map.put("isneedupdateshopXY",isneedupdateshopXY+"");//0设置坐标，1门店无坐标
        map.put("checkTime",getTime());
        saveData();
        try {
            OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                @Override
                public void onSuccess(String result) {
                    String[] strings = result.split("\\|");
                    if (strings[0].equals("201")) {
                        showAnimaDialog(WrittingEvaluationListActivity.this,strings[1]);
                    }else if (strings[0].equals("200")){
                        showAnimaDialog(WrittingEvaluationListActivity.this,"签到成功");
                        final AsynData data=new AsynData(null);
                            new Thread() {
                                @Override
                                public void run() {
                                    super.run();
                                    try {
                                        data.asynSignUpData(MainActivity.id);
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }.start();
                    }else{
                        showToast(WrittingEvaluationListActivity.this,"签到失败");
                        finish();
                    }
                }
                @Override
                public void onFailture() {
                    //离线情况
                    showAnimaDialog(WrittingEvaluationListActivity.this,"签到成功");
                }
            },map);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void showDialog(LatLng myPosition,LatLng shopPosition){
        double Redistance= DistanceUtil.getDistance(myPosition,shopPosition);
        //如果转化失败会返回-1，防止点击进入
        if (Redistance==-1){
            BaseActivity.showAnimaDialog(this,"正在定位，请稍后");
            return;
        }
        if(Redistance>=1000) {
            isinrange = 0;
        }else {
            isinrange = 1;
        }
        dialog=new Dialog(this);
        View view= LayoutInflater.from(this).inflate(R.layout.sign_dialog, (ViewGroup) getWindow().getDecorView(),false);
        TextView countText= (TextView) view.findViewById(R.id.countText);
        final TextView doSign= (TextView) view.findViewById(R.id.doSign);
        doSign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                doSignRequest();
            }
        });
        TextView cancel_action= (TextView) view.findViewById(R.id.cancel_action);
        cancel_action.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                finish();
            }
        });

        if (Redistance>=1000){
            double dd=Redistance/1000;
            double distance=Math.round(dd*10)/10.0;
            countText.setText(distance+"千米");
        }else{
            double distance=Math.round(Redistance*10)/10.0;
            countText.setText(distance+"米");
        }
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(view);
        dialog.show();
    }

    //用户签出
    protected SignUpInfo sui;
    public void signout()
    {
        try {
            sui = db.selector(SignUpInfo.class).where("_ID", "=", MainActivity.signId + "").findFirst();
            if(sui!=null) {
                sui.setOutTime(BaseActivity.getNowDate());
                Map<String,String> map=new HashMap<>();
                map.put("task","signoutsync");
                map.put("siJson", JSON.toJSONString(sui));
                try {
                    OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                        @Override
                        public void onSuccess(String result) {
                            String[] array=result.split("\\|");
                            if(array[0].equals("200")) { //迁出成功
                                try {
                                    db.saveOrUpdate(sui);
                                } catch (DbException e) {
                                    e.printStackTrace();
                                }
                                MainActivity.signId=0;
                                //签到
//                                new Thread(){
//                                    @Override
//                                    public void run() {
//                                        super.run();
//                                        doSignRequest();
//                                    }
//                                }.start();
                                signIn();
                            }
                            else
                            {
                                showAnimaDialog(WrittingEvaluationListActivity.this,"签出失败，参数错误");
                                finish();
                            }
                        }
                        @Override
                        public void onFailture() {
                            try {
                                db.saveOrUpdate(sui);
                            } catch (DbException e) {
                                e.printStackTrace();
                            }
                            //离线签到
                            saveData();
                            showToast(WrittingEvaluationListActivity.this,"签到成功");
                        }
                    },map);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }catch (DbException e) {
            e.printStackTrace();
        }
    }
}
